#include "Delayer.h"

/**
 * delayer to get high or low
 * @param 
 * @return
 */
void delayer(Mat input, Mat destIn, int param, double r, double l)
{

	medianBlur(input,input,35);
	Mat dest = Mat(input.rows, input.cols, CV_8UC1);
	cvtColor(input,dest,CV_BGR2GRAY);
	int histSize = 256;

	// Set the ranges ( for B,G,R) )
	float range[] = { 0, 256 } ;
	const float* histRange = { range };
	bool uniform = true; bool accumulate = false;
	Mat hist;
	Rect R;

	R.x=l*input.cols;
	R.y=l*input.rows;
	R.width=(1-l*2)*input.cols;
	R.height=(1-l*2)*input.rows;
	Mat Hdest=dest(R);
	/// Compute the histograms:
	calcHist( &dest, 1, 0, Mat(), hist, 1, &histSize, &histRange, uniform, accumulate );

	double aveG=0;
	for(int i=0;i<hist.rows;i++)
	{

		aveG+=hist.at<float>(i)/(dest.cols*dest.rows)*i;
	}
	
	if(param == DELAYER_LOW)
	{
		for (int i=0;i<dest.rows;i++)
		{
			for(int j=0;j<dest.cols;j++)
			{

				double r=aveG-dest.at<uchar>(i,j);
				if(r>0)
					dest.at<uchar>(i,j)=r;
				else
					dest.at<uchar>(i,j)=0;
			}
		}

	}
	else
	{
		for (int i=0;i<dest.rows;i++)
		{
			for(int j=0;j<dest.cols;j++)
			{

				double r=dest.at<uchar>(i,j)-aveG;
				if(r>0)
					dest.at<uchar>(i,j)=r;
				else
					dest.at<uchar>(i,j)=0;
			}
		}

	}
	cvtColor(dest, destIn, CV_GRAY2BGR);
}
